/*
 * Create:      刘丹
 * CreateDate:  2023/7/31
 * Describe：   电子病历模板-自研emr
 * */
import React from 'react';
import CaseInformationPageTabs from './CaseInformationPageTabs.jsx';
import DoctorAdviceStepPage from 'pages/workstation/component/DoctorAdviceStepPage';
import ShowDiagnosisModal from 'pages/common/ShowDiagnosisModal.jsx';
import store from 'store';
import { Modal } from 'antd';
import { $http } from 'containers/config/https';
import COS from 'cos-js-sdk-v5';

class CaseInformationNewEmr extends React.Component {
  constructor(props) {
    super(props);
    // 登录用户数据 hospCode userCode userName locID
    var userData = React.$getSessionData(); // 
    // 病人数据 admID, patID
    const recordData = React.$getSessionData('patientData');
    const { historyAdmID = '' } = this.props || {};
    this.state = {
      recordData,
      historyAdmID: historyAdmID || recordData.admID,
      userData,
      treeSelectData: {},
      modalRowData: {},
      iframeUrl: '',
      ref: React.createRef(),
      diagnosisSearch: false, // 诊断录入显示
      medicalOrderVisible: false, // 医嘱录入显示
      doctorAdviceRef: null,
      showDiagnosisChild: null,
    };
  }
  componentDidMount () {
    this.getDefaultTemplate();
    this.initIframeUrl();
  }
  // 接收emr的数据
  getMessage = () => {
    window.addEventListener('message', (event) => {
      let { data } = event;
      if (!data) {
        return;
      }
      if (typeof data === 'string') {
        data = JSON.parse(data);
        const { openName } = data;
        // 打开医嘱
        if (openName === 'openHisdoctorAdvice') {
          this.setState({
            medicalOrderVisible: true,
          }, function () {
            this.depAdviceRef && this.depAdviceRef.loadData();
          });
        }
        // 打开诊断
        if (openName === 'openHisdiagnosis') {
          this.setState({
            diagnosisSearch: true,
          });
        }
      }
    });
  }
  // 获取板分组科室下默认模板右侧引用数据组件需要的传值获取
  getDefaultTemplate = () => {
    $http.post('urlS', this, {
      code: '06010094',
      data: {
        params: [{
          admID: this.state.historyAdmID,
          admLanguage: this.state.userData.admLanguage || 'CN',
        }],
      },
      success: (res) => {
        if (+res.errorCode === 0) {
          const { dataAry = [] } = res.result;
          const data = dataAry[0] || {};
          const treeSelectData = {
            ...data,
            ID: data.wTemplateCatID || '',
          }
          const modalRowData = {
            ...data,
            ID: data.templateID || '',
            releaseVersion: data?.eMRReleaseVersion,
          }
          this.setState({
            treeSelectData,
            modalRowData,
          }, function () {
            // 获取知识数据
            this.getChildKnowledgeBaseTreeData();
          });
        }
      }
    })
  }
  // 初始化IFRAM地址的url地址
  initIframeUrl = () => {
    // const baseUrl = `http://localhost:5173/nav/editorEdit`;
    const baseUrl = 'http://m00.puruiit.cn:3592/nav/editorEdit';
    const { historyAdmID } = this.state;
    const { hospCode, userCode, userName, locID } = this.state.userData;
    const deptCode = this.props?.locID || locID;
    const { groupCode } = this.props.componentSource?.Paras || {};
    $http.post('urlS', this, {
      code: '06090001',
      data: {
        params: [{}],
      },
      success: (res) => {
        if (+res.errorCode === 0) {
          const url = `${baseUrl}?admID=${historyAdmID}&hospitalCode=${hospCode}&loginUserCode=${userCode}&userDesc=${userName}&deptCode=${deptCode}&token=${res.result?.token}&groupCode=${groupCode}`;
          this.setState({
            iframeUrl: url,
          });
          this.getMessage();
        }
      },
    })
  }
  /**
   * 
   * @param {*} data 要引用的内容
   * @param {*} isCover 是否覆盖数据，默认追加组件内容
   * @returns 
   */
  rightQuote = (data, isCover = false) => {
    if (typeof (data) !== 'string') {
      return;
    }
    const iframe = this.state.ref?.current;
    iframe.contentWindow.postMessage(JSON.stringify({
      openName: 'componentDataQuote',
      text: data,
      isCover,
    }), '*');
  }
  // 右侧知识库引用
  rightKnowledgeQuotev = (field, value) => {
    this.rightQuote(value);
  }
  // 赋值知识库对象
  handleCaseInformationRef = ref => {
    this.caseInformationChild = ref;
  }
  // 获取知识库数据
  getChildKnowledgeBaseTreeData = () => {
    this.caseInformationChild.getKnowledgeBaseTreeData('1', this.state.modalRowData);
  }
  /**
    * @ByShizi: 新增医嘱录入弹窗操作
    * Create 2022-08-10
  * */
  handleMedicalOrderOk = async (clickSource) => {
    const ruleOfReferences = await this.getRuleOfReference('QuoteResourcesOrder');
    // 插入诊断前先判断是否有需要保存的数据
    let isSave = this.depAdviceRef && this.depAdviceRef.handleDetermineWhetherToSave
      ? this.depAdviceRef.handleDetermineWhetherToSave()
      : true;
    if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
      this.depAdviceRef.insuTypeCodeFlagFun && this.depAdviceRef.insuTypeCodeFlagFun(clickSource);
    } else {
      let medOrderArr = this.depAdviceRef && this.depAdviceRef.getSelectedRows
        ? this.depAdviceRef.getSelectedRows()
        : [];
      medOrderArr = medOrderArr && medOrderArr.filter(item => !!(item.ordMedItemDesc));
      if (medOrderArr && medOrderArr.length > 0) {
        let domValue = this.handleRuleReference(medOrderArr, ruleOfReferences ? ruleOfReferences : 'ordMedItemDesc');
        this.rightQuote(domValue, true);
        this.setState({
          medicalOrderVisible: false,
        });
      } else {
        message.error('请勾选或者录入医嘱再进行插入。');
      }
    }
  }
  // 获取配置的引用规则
  getRuleOfReference = async (ruleCode) => {
    let ruleOfReferences = '';
    try {
      let data = {
        params: [{
          power: 'DocEMRResource',
          eMRResourceRuleCode: ruleCode
        }]
      }
      let res = await React.$asyncPost(this, '06010079', data);
      ruleOfReferences = res?.result || '';
      // ruleOfReferences = ruleOfReferences.replace('medDesc', 'ordMedItemDesc'); // 医嘱名称
      // ruleOfReferences = ruleOfReferences.replace('ordUsageDesc', 'ordUsageDesc'); // 用法 
      ruleOfReferences = ruleOfReferences.replace('ordDoseUnit', 'ordDoseQtyUnit'); // 剂量 
      ruleOfReferences = ruleOfReferences.replace('ordFreqDesc', 'ordFrequenceDesc'); // 频次
      // ruleOfReferences = ruleOfReferences.replace('ordbodyPartDesc', 'ordbodyPartDesc'); // 部位
    } catch (error) {
      ruleOfReferences = '';
      console.log(error)
    }
    return ruleOfReferences;
  }
  // 医嘱引用规则文案处理
  handleRuleReference = (arr, values) => {
    let insertMethod = this.depAdviceRef && this.depAdviceRef.getInsertMethod
      ? this.depAdviceRef.getInsertMethod()
      : 'transverse'; // 横排： transverse  竖排： vertical
    let valueArr = values.split('+');
    let str = ''
    for (let i = 0; i < arr.length; i++) {
      str += i + 1 + '、';
      for (let j = 0; j < valueArr.length; j++) {
        if (arr[i][valueArr[j]]) {
          str += arr[i][valueArr[j]] + '  ';
        }
      }
      str += (insertMethod === 'vertical' ? ((i === arr.length - 1) ? '' : '</br>') : '  ');
    }
    return str;
  }
  // 插入诊断
  handleDiagnosisSearchOk = (clickSource) => {
    // 插入诊断前先判断是否有需要保存的数据
    let isSave = this.showDiagnosisChild && this.showDiagnosisChild.handleDetermineWhetherToSave
      ? this.showDiagnosisChild.handleDetermineWhetherToSave()
      : true;
    if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
      this.showDiagnosisChild.saveDiagnosisMsg && this.showDiagnosisChild.saveDiagnosisMsg(clickSource);
    } else {
      let diagDescArr = this.showDiagnosisChild && this.showDiagnosisChild.getSelectedRows
        ? this.showDiagnosisChild.getSelectedRows()
        : [];
      if (diagDescArr && diagDescArr.length > 0) {
        this.handleInsertDiagnosis(diagDescArr, 'checkout');
      } else {
        let { diagnosisRowData } = this.state;
        let recordData = sessionStorage.getItem('patientData')
          ? JSON.parse(sessionStorage.getItem('patientData'))
          : {};
        let data = {
          params: [{
            admID: recordData && recordData.admID ? recordData.admID : ''
          }]
        }
        $http.post('urlS', this, {
          code: diagnosisRowData && diagnosisRowData.serviceCode ? diagnosisRowData.serviceCode : '',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              let diagnosisSourse = res.result;
              this.handleInsertDiagnosis(diagnosisSourse);
            }
          }
        })
      }
    }
  }
  // 插入诊断
  handleInsertDiagnosis = (diagnosisSourse, sourse) => {
    const insertMethod = this.showDiagnosisChild && this.showDiagnosisChild.getInsertMethod
      ? this.showDiagnosisChild.getInsertMethod()
      : 'transverse'; // 横排： transverse  竖排： vertical
    if (diagnosisSourse && diagnosisSourse.length > 0) {
      let domValue = '';
      for (var k = 0; k < diagnosisSourse.length; k++) {
        domValue += (k + 1) + '、' + diagnosisSourse[k] + (insertMethod === 'vertical' ? ((k === diagnosisSourse.length - 1) ? '' : '</br>') : '  ');
      }
      this.rightQuote(domValue, true);
    } else {
      message.error('请勾选或者录入同类诊断再进行插入。');
      return;
    }
    this.handleDiagnosisSearchCancel(); // 关闭插入弹窗
  }
  // 关闭诊断弹窗
  handleDiagnosisSearchCancel = () => {
    this.setState({
      diagnosisSearch: false,
    });
  }
  render () {
    return (
      <>
        <div style={{
          height: store.getState().tableHeight.y + 158, display: 'flex'
        }}>
          <iframe
            ref={this.state.ref}
            src={this.state.iframeUrl}
            frameborder="0"
            style={{ height: '100%', flex: 1, }}
          ></iframe>
          <div style={{ width: '500px', height: '100%' }}>
            <CaseInformationPageTabs
              modalRowData={this.state.modalRowData}
              historyAdmID={this.state.historyAdmID}
              treeSelectData={this.state.treeSelectData}
              handleQuote={this.rightQuote}
              onRef={this.handleCaseInformationRef}
              knowledgeBaseAssignment={this.rightKnowledgeQuotev}
            />
          </div>
        </div >
        <Modal
          title="诊断录入"
          visible={this.state.diagnosisSearch}
          onOk={() => this.handleDiagnosisSearchOk("confirm")}
          style={{ minWidth: '75vw' }}
          onCancel={this.handleDiagnosisSearchCancel}
          className="electronic-case-template-modal"
        >
          <div style={{ width: "100%" }}>
            <ShowDiagnosisModal
              onRef={ref => this.showDiagnosisChild = ref}
              handleDiagnosisSearchOk={this.handleDiagnosisSearchOk}
            />
          </div>
        </Modal>

        <Modal
          title="医嘱录入"
          visible={this.state.medicalOrderVisible}
          onOk={() => this.handleMedicalOrderOk('confirm')}
          style={{ minWidth: '75vw' }}
          onCancel={() => this.setState({ medicalOrderVisible: false })}
          className="electronic-case-template-modal"
        >
          <div style={{ width: '100%', height: '55vh' }}>
            <DoctorAdviceStepPage
              patStatus="1"
              heightVH={46}
              componentSourse="EMR" // 用于区分住院，列表数据保存之后是否清空
              // adviceList={this.state.adviceList}
              // ordPriorityID={this.state.priorityID}
              hideStatus={false}
              onRef={ref => this.depAdviceRef = ref}
              handleMedicalOrderOk={this.handleMedicalOrderOk}
            // dstroyAdviceList={this.dstroyAdviceList.bind(this)}
            />
          </div>
        </Modal>
      </>
    )
  }
};
export default CaseInformationNewEmr;